<template>
  <div class="light-green lighten-5">
    <h3 class="py-3" v-show="this.$route.query.keyword">找到{{messages.length}}条记录</h3>
    <my-feed 
      :feed="message" 
      @queryFeed="queryFeedByContent(keyword)" 
      v-for="message in messages" 
      :key="message.forwardId +'#'+ message.feedId">
    </my-feed>
    <el-empty v-show="this.$route.query.keyword && messages.length == 0" description="未找到动态"></el-empty>
  </div>
</template>

<script>
import MyFeed from '../views/MyFeed.vue'

export default {
  name: 'MySearchFeed',
  components: {MyFeed},
  data: ()=>({
    messages: [],
    keyword: ''
  }),
  watch: {
    $route: {
      handler() {
        this.keyword = this.$route.query.keyword;
        this.queryFeedByContent(this.keyword); //这段话是我自己写的函数，在每次参数发生变化时运行
      },
      deep: true
    }
  },
  computed: {
    user(){
      return this.$store.state.user
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      const keyword = to.query.keyword;
      // 根据路由id，查询并设置feed的信息
      vm.queryFeedByContent(keyword)
    })
  },
  methods:{
    doQueryFeedByContent(url, config){
      this.$utils.doGetAxios(this, url, config, (data)=>{
        this.messages = data.map((item,)=>{
          if(item.forwardId){
            item.forwardTime = this.$utils.dateFormat(item.forwardTime)
            item.time = this.$moment(item.time).format("YYYY-MM-DD HH:mm:ss")
          }else{
            item.time = this.$utils.dateFormat(item.time)
          }

          item.showComment = false,
          item.sendContent = '',
          item.comments = []
          return item
        })
      })
    },
    queryFeedByContent(keyword){
      if(!keyword) return

      const userId = this.user.userId
      const token = this.user.token

      if(userId && token){
        this.doQueryFeedByContent('/api/search/feed/u', {
          params:{keyword, userId},
          headers: {token }
        })
      }else{
        this.doQueryFeedByContent('/api/search/feed', {params: {keyword}})
      }
    }
  }
}
</script>

<style>

</style>